package com.derbysoft.synxisadapter.commons.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

public class MailSender implements Runnable {
    private static Log logger = LogFactory.getLog(MailSender.class);
    private static final String SPLIT_CHAR = ";";

    private JavaMailSender mailSender;
    private String subject;
    private String contents;

    public MailSender(JavaMailSender mailSender, String subject, String contents) {
        this.mailSender = mailSender;
        this.subject = subject;
        this.contents = contents;
    }

    @Override
    public void run() {
        send();
    }

    private void send() {
        try {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom(EnvironmentUtils.getMailFromAddress());
            simpleMailMessage.setTo(getAddresses(EnvironmentUtils.getMailToAddress()));
            if (getAddresses(EnvironmentUtils.getCCAddress()) != null) {
                simpleMailMessage.setCc(getAddresses(EnvironmentUtils.getCCAddress()));
            }
            simpleMailMessage.setSubject(subject);
            simpleMailMessage.setText(contents);

            mailSender.send(simpleMailMessage);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }
    }

    private String[] getAddresses(String addresses) {
        if (StringUtils.isBlank(addresses)) {
            return null;
        }
        if (addresses.contains(SPLIT_CHAR)) {
            return StringUtils.split(addresses, SPLIT_CHAR);
        }
        return new String[]{addresses};
    }
}
